import logging

import requests
# from django.core.cache import cache
from django.contrib.auth.models import Group, User
from django.db.models import Q

# import collections


# from main import models as app_models
# from main import config
# from main.common.decorators import decorate_cache


logger = logging.getLogger(__name__)


def dictfetchall(cursor):
    "Returns all rows from a cursor as a dict"
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
    ]


def qq_captcha_validate(ticket, randstr, uip, logger=logger):
    """
    腾讯验证码校验

    return: res: bool
    """

    captcha_url = "https://ssl.captcha.qq.com/ticket/verify"
    post = {
        "aid": "2072676418",
        "AppSecretKey": "0Xl7IzSpn8K2UfaVLKcsVkg**",
        "Ticket": ticket,
        "Randstr": randstr,
        "UserIP": uip,
    }
    response = requests.post(
        url=captcha_url,
        data=post
    )
    logger.info(
        "[REQUEST QQ CAPTCHA] url:{}, post_data:{}, code:{}, response:{}".format(
            captcha_url, post, response, response.content))
    if response.status_code == requests.codes.ok:
        res_data = response.json()
        return res_data['response'] == '1'
    return False


def get_client_ip(request):
    if 'HTTP_X_REAL_IP' in request.META:
        ip = request.META['HTTP_X_REAL_IP']
    elif 'HTTP_X_FORWARDED_FOR' in request.META:
        ip = request.META['HTTP_X_FORWARDED_FOR']
    else:
        ip = request.META['REMOTE_ADDR']
    return ip


def get_permission_user(permission_code):
    groups = Group.objects.filter(permissions__codename=permission_code).values_list('id', flat=True)
    user = User.objects.filter(
        Q(groups__in=groups) | Q(user_permissions__codename=permission_code)).values_list('id', flat=True)

    return list(set(user))


def model_to_dict_by_fields(instance, fields):
    '''
    model_to_dict_by_fields
    '''
    return {field: getattr(instance, field, None)for field in fields}

